const {targetData} = require("../target-file");


let PORT_INSTANCE = undefined;

// 等待 time 毫秒
let sleep = (time) => new Promise((resolve) => {
    setTimeout(resolve, time)
})

let delay = (delay) => {
    return () => {
        return new Promise((resolve, reject) => {
            setTimeout(resolve, delay)
        })
    }
}

// 复位设备
function resetDevice() {
    new Promise((resolve) => {
        console.log('Resetting device: ', PORT_INSTANCE.path)
        resolve()
    }).then(delay(100)).then(() => {
        PORT_INSTANCE.rts = 1;
        console.log('resetDevice ', new Date())
    }).then(delay(100)).then(() => {
        PORT_INSTANCE.rts = 0;
        console.log('resetDevice ', new Date())
    }).then(delay(100)).then(() => {
        PORT_INSTANCE.rts = 1;
        console.log('resetDevice ', new Date())
    })
}

function startBoot() {
    new Promise((resolve) => {
        console.log('Starting bootloader')
        resolve()
    }).then(delay(1)).then(() => {
        PORT_INSTANCE.rts = 1;
        console.log('startBoot ', new Date())
    }).then(delay(100)).then(() => {
        PORT_INSTANCE.rts = 0;
        console.log('startBoot ', new Date())
    }).then(delay(1)).then(() => {
        console.log('startBoot ', new Date());
        const uint8Array = new Uint8Array(64);
        uint8Array.fill(0xF8, 0, uint8Array.length)
        PORT_INSTANCE.write(uint8Array);
        PORT_INSTANCE.drain(err => {
            if (err) {
                console.log('Serial send err: ', err)
                return;
            }
            console.log('Serial send complete')
        });
    }).then(delay(1)).then(() => {
        const buffer = Buffer.alloc(6);
        PORT_INSTANCE.on('readable', () => {
            PORT_INSTANCE.read(buffer, 0, 6)
            console.log(buffer)
        })
    })
}

function bootStage2() {

}

function download(instance) {
    PORT_INSTANCE = instance;

    let promise = new Promise(resolve => {
        resolve()
    }).then(delay(1)).then(() => {
        resetDevice()
    }).then(delay(1)).then(() => {
        startBoot()
    }).then(delay(1)).then(() => {
        bootStage2()
    });

    // 发送数据
    // let respLen = 1;
    // const buffer = Buffer.alloc(1);
    // let isComplete = false;
    // while (!isComplete) {
    //     PORT_INSTANCE.read(buffer, 0, respLen).then(({bytesRead}) => {
    //         console.log('Serial resp: ', bytesRead);
    //
    //         // XModule 协议帧
    //         const frame = new Uint8Array(128);
    //         const len = targetData.read(frame);
    //         if (!len) {
    //             isComplete = true
    //             return
    //         }
    //
    //         // 发送协议帧
    //         write(frame, 0, len);
    //     }, err => {
    //         if (err) {
    //             console.log('Serial err: ', err);
    //         }
    //     })
    // }
}

function write(frame, offset, len) {
    let data;
    if (frame.length !== len) {
        const dataLen = frame.length - offset - (frame.length - len);
        data = new Uint8Array(dataLen);
        data.copyWithin(frame, offset, len);
        // 发送协议帧
        PORT_INSTANCE.write(data);
        return;
    } else {
        data = frame;
    }
    PORT_INSTANCE.write(data);

    // 等待数据发送完成
    PORT_INSTANCE.drain(err => {
        if (err) {
            console.log('port error:', err)
            return
        }
        console.log('Seria Write complete, ', PORT_INSTANCE.path)
    });
}

exports.download = download;